import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:image_picker/image_picker.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import '../services/index.dart';

/// 图片选择结果
class ImagePickerResult {
  final bool success;
  final String? imagePath;
  final String? errorMessage;
  final ImagePickerError? error;
  
  const ImagePickerResult({
    required this.success,
    this.imagePath,
    this.errorMessage,
    this.error,
  });
  
  /// 成功结果
  factory ImagePickerResult.success(String imagePath) {
    return ImagePickerResult(
      success: true,
      imagePath: imagePath,
    );
  }
  
  /// 失败结果
  factory ImagePickerResult.failure(String errorMessage, [ImagePickerError? error]) {
    return ImagePickerResult(
      success: false,
      errorMessage: errorMessage,
      error: error,
    );
  }
}

/// 图片选择错误类型
enum ImagePickerError {
  permissionDenied,    // 权限被拒绝
  permanentlyDenied,   // 权限被永久拒绝
  noImageSelected,     // 用户取消选择
  deviceNotSupported,  // 设备不支持
  unknown,             // 未知错误
}

/// 图片选择工具类
/// 
/// 提供统一的图片选择、权限申请、图片处理功能
/// 纯逻辑封装，无UI依赖，便于复用和测试
class ImagePickerHelper {
  static const String tag = 'ImagePickerHelper';
  
  // 单例实例
  static final ImagePickerHelper _instance = ImagePickerHelper._internal();
  factory ImagePickerHelper() => _instance;
  ImagePickerHelper._internal();
  
  // 图片选择器实例
  final ImagePicker _imagePicker = ImagePicker();
  
  // 权限服务
  PermissionService get _permissionService => Get.find<PermissionService>();

  /// 从相机拍照
  /// 
  /// [maxWidth] 图片最大宽度
  /// [maxHeight] 图片最大高度
  /// [imageQuality] 图片质量 (0-100)
  /// 返回图片选择结果
  Future<ImagePickerResult> pickImageFromCamera({
    double? maxWidth = 1080,
    double? maxHeight = 1080,
    int imageQuality = 85,
  }) async {
    try {
      debugPrint('$tag: 开始从相机拍照');
      
      // 申请相机权限
      final cameraResult = await _permissionService.requestCameraPermission();
      if (!cameraResult.isGranted) {
        debugPrint('$tag: 相机权限被拒绝 - ${cameraResult.message}');
        
        final error = cameraResult.status == PermissionStatus.permanentlyDenied
            ? ImagePickerError.permanentlyDenied
            : ImagePickerError.permissionDenied;
            
        return ImagePickerResult.failure(cameraResult.message, error);
      }
      
      // 使用相机拍照
      final XFile? image = await _imagePicker.pickImage(
        source: ImageSource.camera,
        maxWidth: maxWidth,
        maxHeight: maxHeight,
        imageQuality: imageQuality,
      );
      
      if (image != null) {
        debugPrint('$tag: 相机拍照成功 - ${image.path}');
        return ImagePickerResult.success(image.path);
      } else {
        debugPrint('$tag: 用户取消拍照');
        return ImagePickerResult.failure('用户取消拍照', ImagePickerError.noImageSelected);
      }
      
    } catch (e) {
      debugPrint('$tag: 相机拍照异常 - $e');
      return ImagePickerResult.failure('拍照失败，请重试', ImagePickerError.unknown);
    }
  }

  /// 从相册选择图片
  /// 
  /// [maxWidth] 图片最大宽度
  /// [maxHeight] 图片最大高度
  /// [imageQuality] 图片质量 (0-100)
  /// 返回图片选择结果
  Future<ImagePickerResult> pickImageFromGallery({
    double? maxWidth = 1080,
    double? maxHeight = 1080,
    int imageQuality = 85,
  }) async {
    try {
      debugPrint('$tag: 开始从相册选择');
      
      // 申请相册权限
      final galleryResult = await _permissionService.requestGalleryPermission();
      if (!galleryResult.isGranted) {
        debugPrint('$tag: 相册权限被拒绝 - ${galleryResult.message}');
        
        final error = galleryResult.status == PermissionStatus.permanentlyDenied
            ? ImagePickerError.permanentlyDenied
            : ImagePickerError.permissionDenied;
            
        return ImagePickerResult.failure(galleryResult.message, error);
      }
      
      // 从相册选择图片
      final XFile? image = await _imagePicker.pickImage(
        source: ImageSource.gallery,
        maxWidth: maxWidth,
        maxHeight: maxHeight,
        imageQuality: imageQuality,
      );
      
      if (image != null) {
        debugPrint('$tag: 相册选择成功 - ${image.path}');
        return ImagePickerResult.success(image.path);
      } else {
        debugPrint('$tag: 用户取消选择');
        return ImagePickerResult.failure('用户取消选择', ImagePickerError.noImageSelected);
      }
      
    } catch (e) {
      debugPrint('$tag: 相册选择异常 - $e');
      return ImagePickerResult.failure('选择图片失败，请重试', ImagePickerError.unknown);
    }
  }

  /// 选择多张图片（从相册）
  /// 
  /// [maxWidth] 图片最大宽度
  /// [maxHeight] 图片最大高度
  /// [imageQuality] 图片质量 (0-100)
  /// 返回图片路径列表
  Future<List<String>> pickMultipleImages({
    double? maxWidth = 1080,
    double? maxHeight = 1080,
    int imageQuality = 85,
  }) async {
    try {
      debugPrint('$tag: 开始选择多张图片');
      
      // 申请相册权限
      final galleryResult = await _permissionService.requestGalleryPermission();
      if (!galleryResult.isGranted) {
        debugPrint('$tag: 相册权限被拒绝');
        return [];
      }
      
      // 从相册选择多张图片（使用pickMultiImage方法）
      final List<XFile> images = await _imagePicker.pickMultiImage(
        maxWidth: maxWidth,
        maxHeight: maxHeight,
        imageQuality: imageQuality,
      );
      
      if (images.isNotEmpty) {
        final imagePaths = images.map((image) => image.path).toList();
        debugPrint('$tag: 选择了${imagePaths.length}张图片');
        return imagePaths;
      } else {
        debugPrint('$tag: 用户取消选择');
        return [];
      }
      
    } catch (e) {
      debugPrint('$tag: 选择多张图片异常 - $e');
      return [];
    }
  }

  /// 获取图片文件信息
  /// 
  /// [imagePath] 图片路径
  /// 返回图片信息
  Future<Map<String, dynamic>?> getImageInfo(String imagePath) async {
    try {
      final file = File(imagePath);
      if (!await file.exists()) {
        debugPrint('$tag: 图片文件不存在 - $imagePath');
        return null;
      }
      
      final stat = await file.stat();
      final size = stat.size;
      
      return {
        'path': imagePath,
        'size': size,
        'sizeInMB': (size / (1024 * 1024)).toStringAsFixed(2),
        'lastModified': stat.modified,
      };
    } catch (e) {
      debugPrint('$tag: 获取图片信息失败 - $e');
      return null;
    }
  }

  /// 检查设备是否支持相机
  /// 
  /// 返回是否支持相机功能
  Future<bool> isCameraSupported() async {
    try {
      // 检查相机权限状态来判断设备是否支持相机
      final cameraStatus = await Permission.camera.status;
      // 如果权限状态不是restricted，说明设备支持相机
      return cameraStatus != PermissionStatus.restricted;
    } catch (e) {
      debugPrint('$tag: 检查相机支持失败 - $e');
      return false;
    }
  }

  /// 清理临时图片文件
  /// 
  /// [imagePath] 要清理的图片路径
  Future<bool> clearTempImage(String imagePath) async {
    try {
      final file = File(imagePath);
      if (await file.exists()) {
        await file.delete();
        debugPrint('$tag: 清理临时图片成功 - $imagePath');
        return true;
      }
      return false;
    } catch (e) {
      debugPrint('$tag: 清理临时图片失败 - $e');
      return false;
    }
  }
}
